package com.its.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import lombok.experimental.Delegate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
@ConditionalOnClass(OssConfig.class)
public class OssAutoConfiguration {
    @Bean
    @ConditionalOnMissingBean(name = {"ossClient"})
    public OSS ossClient(OssConfig ossConfig) {
        return new OSSClientWrapper(ossConfig);
    }

    private static class OSSClientWrapper implements OSS, DisposableBean {
        @Delegate
        private final OSS delegate;

        private OSSClientWrapper(OssConfig ossConfig) {
            this.delegate = new OSSClientBuilder()
                    .build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        }

        @Override
        public void destroy() throws Exception {
            if (delegate != null) {
                delegate.shutdown();
                log.info("OSSClient已通过DisposableBean释放");
            }
        }
    }
}
